package org.example.apitest.state;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.*;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.example.apitest.beans.SensorReading;

public class StateTest2KeyedState {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);
        env.getConfig().setAutoWatermarkInterval(100);

        // 从socket中读取数据
        DataStream<String> inputStream = env.socketTextStream("localhost", 7777);

        // 转换为SensorReading类型
        DataStream<SensorReading> dataStream = inputStream
                .map((MapFunction<String, SensorReading>) SensorReading::new);

        // 定义一个有状态的map操作,统计当前分区数据个数
        SingleOutputStreamOperator<Integer> resultStream = dataStream.keyBy("id")
                .map(new RichMapFunction<SensorReading, Integer>() {
                    private ValueState<Integer> keyCountState;
                    private ListState<Integer> listCountState;
                    private MapState<String, Double> mapState;
                    private ReducingState<SensorReading> reducingState;

                    @Override
                    public void open(Configuration parameters) throws Exception {
                        keyCountState = getRuntimeContext().getState(new ValueStateDescriptor<>("key-count", Integer.class));
                        listCountState = getRuntimeContext().getListState(new ListStateDescriptor<>("list-count", Integer.class));
                        mapState = getRuntimeContext().getMapState(new MapStateDescriptor<String, Double>("map-count", String.class, Double.class));
//                        reducingState=getRuntimeContext().getReducingState(new ReducingStateDescriptor<SensorReading>())
                        if (keyCountState.value() == null) {
                            keyCountState.update(0);
                        }
                    }

                    @Override
                    public Integer map(SensorReading value) throws Exception {
                        Integer count = keyCountState.value();
                        count++;
                        keyCountState.update(count);
                        return count;
                    }
                });

        resultStream.print();

        env.execute();
    }
}
